<template>
    <div class="approve">
        <el-card class="box_card">
            <template #header>
                <div class="card-header">
                    <span>实名信息</span>
                </div>
            </template>
            <!--小提示-->
            <div class="tip">
                <p><el-icon><InfoFilled/></el-icon>完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证。</p>
            </div>
            <!-- 卡片展示信息部分，分为两种情况 -->
            <!-- 1.未认证，展示认证结构 -->
            <div v-show="Status === 0">
                <el-form style="margin: 20px auto;width: 50%" label-width="80px" :model="formData" :rules="rules" ref="form">
                    <el-form-item label="用户姓名" prop="name">
                        <el-input placeholder="请输入用户姓名" clearable v-model="formData.name"></el-input>
                    </el-form-item>
                    <el-form-item label="证件类型" prop="certificatesType">
                        <el-select placeholder="请选择证件类型" v-model="formData.certificatesType">
                            <el-option :label="item.name" v-for="(item,index) in typeList" :key="index" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证件号码" prop="certificatesNo">
                        <el-input placeholder="请输入证件号码" clearable v-model="formData.certificatesNo"></el-input>
                    </el-form-item>
                    <el-form-item label="上传证件" prop="certificatesUrl">
                        <!-- action upload组件向服务器提交照片路径，limit限制一张照片，on-exceed超出约束数量的钩子-->
                        <el-upload list-type="picture-card"
                                   ref="upload"
                                   :limit="1"
                                   :on-exceed="notice"
                                   :on-success="successUpload"
                                   :on-preview="preview"
                                   :on-remove="remove"
                                   action="/api/oss/file/fileUpload?fileHost=userAuah">
                            <img src="@/assets/待上传.png" alt="">
                        </el-upload>
                        <!--预览照片-->
                        <el-dialog v-model="dialogVisible">
                            <img w-full v-if="formData.certificatesUrl" :src="formData.certificatesUrl" alt="Preview Image" style="width: 100%;height: 100%"/>
                        </el-dialog>
                    </el-form-item>
                    <el-form-item >
                        <el-button type="primary" size="default" @click="reset">清空</el-button>
                        <el-button type="primary" size="default" @click="submit">提交</el-button>
                    </el-form-item>
                </el-form>
                <el-button type="primary" size="default" @click="Status=1">返回</el-button>
            </div>
            <!-- 2.认证成功的展示 -->
            <div v-show="Status===1">
                <el-descriptions
                    class="margin-top"
                    :column="1"
                    border
                    style="margin: 20px 0"
                >
                    <el-descriptions-item width="30px" label-align="center">
                        <template #label>
                            <div class="cell-item">
                                用户姓名
                            </div>
                        </template>
                        {{ userInfo?.name }}
                    </el-descriptions-item>
                    <el-descriptions-item width="30px" label-align="center">
                        <template #label>
                            <div class="cell-item">
                                证件类型
                            </div>
                        </template>
                        {{ userInfo?.certificatesType=='10'?'身份证':'户口本' }}
                    </el-descriptions-item>
                    <el-descriptions-item width="30px" label-align="center">
                        <template #label>
                            <div class="cell-item">
                                证件号码
                            </div>
                        </template>
                        {{ userInfo?.certificatesNo}}
                    </el-descriptions-item>
                </el-descriptions>
                <div style="text-align: center">
                    <el-button type="primary" size="default" @click="Status=0">重新认证</el-button>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts" name="Approve">
    import {InfoFilled} from "@element-plus/icons-vue";
    import {reqUserInfo,reqIdType,reqUserAudit} from "@/api/user";
    import type {UserInfoResponseData, UserInfo, IdTypeResponseData, idTypeList, UserParams} from "@/api/user/type";
    import {onMounted, reactive, ref} from "vue";
    import {ElMessage} from "element-plus";

    //存储用户信息
    const userInfo = ref<UserInfo>();
    // 认证状态
    const Status = ref()
    // 获取证件类型
    const typeList = ref<idTypeList>([]);
    // 表单实例
    const form = ref();
    // 上传图片组件实例
    const upload = ref();
    // 收集表单中的数据
    const formData = reactive<UserParams>({
        certificatesUrl: "",
        certificatesType:"",
        certificatesNo:"",
        name:""
    })
    // 控制预览的显示
    const dialogVisible = ref(false);

    onMounted(()=>{
        getUserInfo();
        getType();
    })
    // 获取用户信息封装方法
    const getUserInfo =async () =>{
        let res:UserInfoResponseData = await reqUserInfo();
        if(res.code===200){
            userInfo.value = res.data;
            Status.value = res.data.status;
        }
    }
    // 获取证件类型的方法
    const getType =async () =>{
        let res:IdTypeResponseData = await reqIdType();
        if(res.code === 200)
        {
            typeList.value = res.data;
        }
    }

    // 超出约束数量的钩子
    const notice = () =>{
        ElMessage.warning("最多上传一张照片");
    }

    // 成功的钩子
    const successUpload =(response:any) =>{
        formData.certificatesUrl = response.data;
        // 上传成功，清除校验结果
        form.value.validateField('checkUrl');
        form.value.validate();
    }

    // 预览图片
    const preview = () =>{
        dialogVisible.value = true;
    }

    // 移除图片
    const remove = () =>{
        formData.certificatesUrl = "";
    }

    // 重置表单
    const reset = () =>{
        // 重置表单
        Object.assign(formData,{
            certificatesType:"",
            certificatesNo:"",
            name:""
        })
        // 清空文件
        upload.value.clearFiles();
        // 清空校验项
        form.value.resetFields();
    }

    // 提交表单
    const submit =async () =>{
        // 校验所有表单元素
        if(await form.value.validate()){
            try {
                await reqUserAudit(formData);
                ElMessage({
                    message: '提交成功',
                    type: 'success'
                });
                // 认证成功后再次获取用户信息
                await getUserInfo();
            } catch (e) {
                ElMessage({
                    message: '提交失败',
                    type: 'error'
                })
            }
        }
    }
    const checkName = (rule:any, value:string, callback:any) =>{
        // rule为当前校验对象规则，value为当前输入的值，callback为校验成功或失败的回调函数
        const reg = /^[\u4e00-\u9fa5]{2,4}(·[\u4e00-\u9fa5]{2,4})?|^[a-zA-Z\s]{2,20}/
        if(reg.test(value)){
            callback();
        }else{
            callback(new Error('请输入正确的姓名'));
        }
    }
    const checkType = (rule:any,value:string,callback:any) =>{
        if(value=='10' || value=='20'){
            callback();
        }else{
            callback(new Error('请选择证件类型'));
        }
    }
    const checkNo = (rule:any,value:string,callback:any) =>{
        const reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
        const reg1 = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        if(reg.test(value) || reg1.test(value)){
            callback();
        }else{
            callback(new Error('请输入正确的身份证号'));
        }
    }
    const checkUrl = (rule:any,value:string,callback:any) =>{
        if(value){
            callback();
        }else{
            callback(new Error('请上传证件照片'));
        }
    }
    // 表单校验规则
    const rules = {
        certificatesType: [
            { required: true, validator:checkType, },
        ],
        certificatesNo: [
            { required: true, validator:checkNo,},
        ],
        name: [
            { required: true, validator: checkName,},
        ],
        certificatesUrl: [
            { required: true, validator:checkUrl,},
        ],
    }
</script>

<style scoped>
    .approve{
        .box_card{
            .tip{
                text-align: center;
                p{
                    color: #7f7f7f;
                    margin: 0;
                    font-size: 12px;
                }
            }
        }
    }
</style>